package com.example.lin.work1;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.File;
import java.io.IOException;

/**
 * 使用 OkHttp 下载图片,下载完成后 在 通知栏显示 大图(下载的图片)通知!  点击通知跳转到 ImageActivity 并显示该图片.
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    private void downloadImage() {
        String imageUrl = "http://sjbz.fd.zol-img.com.cn/t_s240x320c/g5/M00/00/04/ChMkJ1fJWBWIWPepAAN6QRtsxmcAAU-IAJOH5cAA3pZ415.jpg";
        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        showProgressNotification("下载", "正在连接资源", 0, true);
        OkUtils.download(imageUrl, directory.getAbsolutePath(), new OkUtils.OnOkDownloadCallback() {

            int current = -1;

            @Override
            public void onProgress(File file, float progress) {
                int p = (int) (progress * 100);
                if (p > current) {
                    showProgressNotification(file.getName(), "已下载" + p + "%", p, false);
                    current = p;
                }
            }

            @Override
            public void onResponse(File file) {
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                intent.putExtra("imagePath", file.getAbsolutePath());

                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());

                showComplete(file.getName(), file.getAbsolutePath(), bitmap, intent);
            }

            @Override
            public void onFailure(IOException e) {

            }
        });


    }

    private static int NOTIFY_ID_COMPLETE = 99999;

    private void showProgressNotification(String fileName, String info, int progress, boolean indeterminate) {
        //Step1:获取通知管理器
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        //在Android(O) 8.0 及以上,需要做以下配置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (manager != null) {
                NotificationChannel notificationChannel = new NotificationChannel(NOTIFY_CHANNEL_ID, NOTIFY_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(notificationChannel);
            }
        }
        //NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        if (manager != null) {
            //Step3: 构造 Notification 对象
            Notification notification = new NotificationCompat.Builder(this, NOTIFY_CHANNEL_ID)
                    //设置通知的 小图标(必须设置,否则通知不显示)
                    .setSmallIcon(R.mipmap.qq2)
                    //通知标题
                    .setContentTitle(fileName)
                    //参数1是:总进度,参数2是:当前进度,参数3是:是否不明确
                    .setProgress(100, progress, indeterminate)
                    //设置 通知 显示的时间
                    .setWhen(System.currentTimeMillis())
                    //通知的内容
                    .setContentText(info)
                    //设置 通知 来时的触发(铃声\震动\闪光)
                    .setDefaults(Notification.DEFAULT_ALL)
                    //构造Notification对象
                    .build();

            notification.flags |= Notification.FLAG_NO_CLEAR; //让通知不能滑动取消
//            notification.flags |= Notification.FLAG_INSISTENT; //重复发出 通知的声音/震动 直到用户点击该通知
//            notification.flags |= Notification.FLAG_ONGOING_EVENT; //让通知 显示 正在运行
//            notification.flags |= Notification.FLAG_AUTO_CANCEL; //让通知被点击之后自动取消掉
//
            //Step2:唤醒通知, 每个 通知的ID 是唯一的.如果ID一样,则通知栏不会创建新的通知,会重用原来的通知
            manager.notify(NOTIFY_ID, notification);
        }
    }


    public void showComplete(String title, String content, Bitmap bitmap, Intent intent) {
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (manager != null) {
                NotificationChannel notificationChannel = new NotificationChannel(NOTIFY_CHANNEL_ID, NOTIFY_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(notificationChannel);
            }
        }
        if (manager != null) {
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                    //大图通知样式 的 大图标
//                    .bigLargeIcon(bigLargeIcon)
                    //大图通知样式的 图片
                    .bigPicture(bitmap)
                    //通知的内容
                    .setSummaryText(content)
                    //通知的标题
                    .setBigContentTitle(title);

            //Step3: 构造 Notification 对象
            Notification notification = new NotificationCompat.Builder(this, NOTIFY_CHANNEL_ID)
                    //设置通知的 小图标(必须设置,否则通知不显示)
                    .setSmallIcon(R.mipmap.qq2)
                    //通知标题
                    .setContentTitle(title)
                    //设置 通知 显示的时间
                    .setWhen(System.currentTimeMillis() - 3600000L)
                    //通知的内容
                    .setContentText(content)
                    //在5.0之前的版本中,当通知刚到达时,在状态栏显示
                    .setTicker(title + ":" + content)
                    //设置 通知 来时的触发(铃声\震动\闪光)
                    .setDefaults(Notification.DEFAULT_ALL)
                    //添加意图对象
                    .setContentIntent(pendingIntent)
                    //设置 通知的样式(大图/长文本)
                    .setStyle(bigPictureStyle)
                    //构造Notification对象
                    .build();

//            notification.flags |= Notification.FLAG_NO_CLEAR; //让通知不能滑动取消
//            notification.flags |= Notification.FLAG_INSISTENT; //重复发出 通知的声音/震动 直到用户点击该通知
//            notification.flags |= Notification.FLAG_ONGOING_EVENT; //让通知 显示 正在运行
            notification.flags |= Notification.FLAG_AUTO_CANCEL; //让通知被点击之后自动取消掉
//
            //Step2:唤醒通知, 每个 通知的ID 是唯一的.如果ID一样,则通知栏不会创建新的通知,会重用原来的通知
            manager.notify(NOTIFY_ID_COMPLETE, notification);
            manager.cancel(NOTIFY_ID);
        }
    }

    public static int NOTIFY_ID = 321;
    private static final String NOTIFY_CHANNEL_ID = "OK_CHANNEL_ID";
    private static final String NOTIFY_CHANNEL_NAME = "OK_CHANNEL_NAME";


    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    public void test2(View view) {
        downloadApk();
    }

    public void test1(View view) {
        downloadImage();
    }
        
    private void downloadApk() {
        String apkUrl = "http://gdown.baidu.com/data/wisegame/c700c09f945b2c51/ximalayaFM_172.apk";

        File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        showProgressNotification("下载", "正在连接资源", 0, true);
        OkUtils.download(apkUrl, directory.getAbsolutePath(), new OkUtils.OnOkDownloadCallback() {

            int current = -1;

            @Override
            public void onProgress(File file, float progress) {
                int p = (int) (progress * 100);
                if (p > current) {
                    showProgressNotification(file.getName(), "已下载" + p + "%", p, false);
                    current = p;
                }
            }

            @Override
            public void onResponse(File file) {

                Intent installApkIntent = getInstallApkIntent(file, MainActivity.this);

                showCompleteInstallApk(file.getName(), file.getAbsolutePath(), installApkIntent);
            }

            @Override
            public void onFailure(IOException e) {

            }
        });
    }


    public void showCompleteInstallApk(String title, String content, Intent intent) {
        NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (manager != null) {
                NotificationChannel notificationChannel = new NotificationChannel(NOTIFY_CHANNEL_ID, NOTIFY_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(notificationChannel);
            }
        }
        if (manager != null) {
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            //Step3: 构造 Notification 对象
            Notification notification = new NotificationCompat.Builder(this, NOTIFY_CHANNEL_ID)
                    //设置通知的 小图标(必须设置,否则通知不显示)
                    .setSmallIcon(R.mipmap.qq2)
                    //通知标题
                    .setContentTitle(title)
                    //设置 通知 显示的时间
                    .setWhen(System.currentTimeMillis())
                    //通知的内容
                    .setContentText(content)
                    //在5.0之前的版本中,当通知刚到达时,在状态栏显示
                    .setTicker(title + ":" + content)
                    //设置 通知 来时的触发(铃声\震动\闪光)
                    .setDefaults(Notification.DEFAULT_ALL)
                    //添加意图对象
                    .setContentIntent(pendingIntent)
                    //构造Notification对象
                    .build();

//            notification.flags |= Notification.FLAG_NO_CLEAR; //让通知不能滑动取消
//            notification.flags |= Notification.FLAG_INSISTENT; //重复发出 通知的声音/震动 直到用户点击该通知
//            notification.flags |= Notification.FLAG_ONGOING_EVENT; //让通知 显示 正在运行
            notification.flags |= Notification.FLAG_AUTO_CANCEL; //让通知被点击之后自动取消掉
            //Step2:唤醒通知, 每个 通知的ID 是唯一的.如果ID一样,则通知栏不会创建新的通知,会重用原来的通知
            manager.notify(NOTIFY_ID_COMPLETE, notification);
            manager.cancel(NOTIFY_ID);
        }
    }


    /**
     * 获得 安装 Apk 的 Intent 对象
     *
     * @param file    Apk 文件（该 File 文件路径所在目录必须在provider_paths.xml 中配置 ）
     * @param context 上下文
     * @return 安装 Apk 的 Intent 对象
     */
    private static Intent getInstallApkIntent(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".FileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        return intent;
    }
}
